import paramiko
from log import WriteLog


class SshRun(WriteLog):
    def __init__(self):
        super(SshRun, self).__init__()

    @staticmethod
    def ssh_connect(ip, username, pwd):
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(ip, 22, username, pwd, timeout=1800)
        return ssh

    def ssh_run(self, ssh, cmd, f_path):
        if f_path:
            self.write_file(f_path, cmd)
        else:
            print(cmd)
        stdin, stdout, stderr = ssh.exec_command(cmd)
        run_res = stdout.read().decode('utf-8').strip()
        er_res = stderr.read().decode('utf-8').strip()
        if er_res:
            self.print_error(f'error: {er_res}')
        return run_res

    def conn_and_run(self, cmd, is_sql=False, **kwargs):
        ssh = self.ssh_connect(kwargs['ip'],
                               kwargs['username'],
                               kwargs['pwd'])
        if is_sql:
            run_cmd = f'source {kwargs["db_env"]}; ' \
                f'gsql -d {kwargs["db_name"]} -p {kwargs["db_port"]} ' \
                f'-c "{cmd}"'
        else:
            run_cmd = cmd
        res = self.ssh_run(ssh, run_cmd, f_path=None)
        self.ssh_close(ssh)

        return res

    @staticmethod
    def ssh_close(ssh):
        ssh.close()
